cmake_minimum_required(VERSION 3.14)

# Google Test配置
include(FetchContent)
FetchContent_Declare(
    googletest
    GIT_REPOSITORY https://github.com/google/googletest.git
    GIT_TAG release-1.12.1
)

# Windows上配置Google Test
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
FetchContent_MakeAvailable(googletest)

# 启用Google Test的CTest集成
include(GoogleTest)

# 收集所有测试文件
file(GLOB_RECURSE TEST_SOURCES "*.cpp")

# 如果没有测试文件，创建一个空的测试目标
if(NOT TEST_SOURCES)
    message(WARNING "No test files found in tests directory")
    return()
endif()

# 为每个测试文件创建测试可执行文件
foreach(test_source ${TEST_SOURCES})
    # 获取文件名（不含扩展名）
    get_filename_component(test_name ${test_source} NAME_WE)
    
    # 创建测试可执行文件
    add_executable(${test_name} ${test_source})
    
    # 链接Google Test
    target_link_libraries(${test_name}
        PRIVATE
        GTest::gtest_main
        GTest::gmock_main
    )
    
    # 如果项目库存在，链接项目库
    if(TARGET ${PROJECT_NAME}_lib)
        target_link_libraries(${test_name} PRIVATE ${PROJECT_NAME}_lib)
    endif()
    
    # 添加测试
    gtest_discover_tests(${test_name}
        WORKING_DIRECTORY ${PROJECT_DIR}
        PROPERTIES VS_DEBUGGER_WORKING_DIRECTORY "${PROJECT_DIR}"
    )
    
    # 设置测试属性
    set_target_properties(${test_name} PROPERTIES
        FOLDER tests
        RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin/tests
    )
endforeach()

# 添加自定义目标来运行所有测试
add_custom_target(run_tests
    COMMAND ${CMAKE_CTEST_COMMAND} --output-on-failure --verbose
    DEPENDS ${TEST_SOURCES}
    WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
    COMMENT "Running all tests"
)
